#include "timer.h"
#include <stdlib.h>
#include <cstring>
#include <unistd.h>

int CreateTimeoutfd(int iTimeoutVal)
{
    int iTimeout = iTimeoutVal;
    int iTimefd = timerfd_create(CLOCK_REALTIME, 0); // CLOCK_REALTIME, CLOCK_MONOTONIC
    if (iTimefd < 0)
    {
        printf("[%s] create timer fd %d failed errno = %d\n", __func__, iTimefd, errno);
        return -1;
    }
    else
    {
        printf("create timer fd success\n");
    }

    if (SetTimeout(iTimefd, iTimeout) < 0)
    {
        printf("[%s] set timer out failed errno = %d\n", __func__, errno);
        close(iTimefd);
        iTimefd = -1;
    }

    return iTimefd;
}

int SetTimeout(int iTimefd, int iTimeout)
{
    struct itimerspec ts;
    memset(&ts, 0, sizeof(struct itimerspec));

    ts.it_value.tv_sec = iTimeout;
    ts.it_interval.tv_sec = iTimeout;
    if (timerfd_settime(iTimefd, 0, &ts, NULL) < 0)
    {
        printf("[%s] timerfd_settime fd failed errno = %d\n", __func__, errno);
        return -1;
    }
    else
    {
        return 0;
    }
}
